# -*- coding: utf-8 -*-
import time
import threading
import pystray
from PIL import Image

import message
import login
import logout
from logger_setup import get_logger, logger
import yaml_tool
import setting

pallet_logger = get_logger("pallet")
# 创建图标图像
image = Image.open("icon.png")  # 请替换为你自己的图标文件路径
cfg_new = yaml_tool.get_dict()
reconnect_status = cfg_new["net"]["reconnect"]


# 定义菜单项的回调函数
def on_quit(icon, item):
    global running
    running = False
    icon.stop()
    pallet_logger.info('系统托盘已退出')


def login_pallet(icon, item):
    pallet_logger.info('执行登陆')
    try:
        if login.login():
            message.MessageBox.info(title="登录", message="登录成功")
            global reconnect_status
            yaml_tool.repair_data(['net', 'reconnect'], 1)
            reconnect_status = 1
        else:
            message.MessageBox.info(title="登录", message="登录失败，请在日志文件查看错误")
    except Exception as e:
        pallet_logger.error(e)
        message.MessageBox.error(title="错误", message="请在日志文件查看错误")


def logout_pallet(icon, item):
    pallet_logger.info('执行登出')
    try:
        logout_result = logout.logout()
        message.MessageBox.info(title="登出", message=logout_result)
        global reconnect_status
        yaml_tool.repair_data(['net', 'reconnect'], 0)
        reconnect_status = 0
    except Exception as e:
        pallet_logger.error(e)
        message.MessageBox.error(title="错误", message="请在日志文件查看错误")


def modify_reconnect(icon, item):
    try:
        global reconnect_status
        if reconnect_status == 0:
            yaml_tool.repair_data(['net', 'reconnect'], 1)
            reconnect_status = 1
        else:
            yaml_tool.repair_data(['net', 'reconnect'], 0)
            reconnect_status = 0
        cfg_new = yaml_tool.get_dict()
        reconnect_new = cfg_new["net"]["reconnect"]
        pallet_logger.info(f'将自动重连设置为{reconnect_new}')
        message.MessageBox.info(title="自动重连状态修改", message=f'将自动重连设置为{reconnect_new}')
    except Exception as e:
        pallet_logger.error(e)
        message.MessageBox.error(title="错误", message="请在日志文件查看错误")


def display_reconnect(icon, item):
    try:
        cfg_new = yaml_tool.get_dict()
        reconnect_new = cfg_new["net"]["reconnect"]
        message.MessageBox.info(title="自动重连状态", message=f"自动重连状态为{reconnect_new}")
        pallet_logger.info('弹窗显示自动重连状态')
    except Exception as e:
        pallet_logger.error(e)
        message.MessageBox.error(title="错误", message="请在日志文件查看错误")


# 创建菜单 (包含一个退出项)
menu = pystray.Menu(
    pystray.MenuItem('登陆', login_pallet),
    pystray.MenuItem('登出', logout_pallet),
    pystray.MenuItem(f'修改自动重连', modify_reconnect),
    pystray.MenuItem(f'显示自动重连状态', display_reconnect),
    pystray.MenuItem('退出', on_quit)
)

try:
    # 创建托盘图标实例
    icon = pystray.Icon(
        "wuhu-tool",  # 应用名称
        image,  # 图标图像
        "wuhu-tool",  # 鼠标悬停提示文本
        menu  # 关联的菜单
    )
except:
    pallet_logger.warning('系统托盘初始化失败')


def reconnect():
    global reconnect_status
    reconnect_logger = get_logger("reconnect_logger")
    while True:
        if reconnect_status == 1:
            running_status = True
        else:
            running_status = False
        while running_status:
            if reconnect_status == 1:
                try:
                    reconnect_message = setting.reconnection()
                    if not reconnect_message:
                        running_status = False
                        reconnect_status = 0
                        yaml_tool.repair_data(['net', 'reconnect'], 0)
                        reconnect_logger.warning("登陆失败，自动重连已关闭")
                        message.MessageBox.warning("自动重连","登陆失败，自动重连已关闭，请查看日志")
                except Exception as e:
                    reconnect_logger.error(e)
            else:
                break
            time.sleep(5)
        time.sleep(2)


if __name__ == "__main__":
    #启动自动开启自动重连
    yaml_tool.repair_data(['net', 'reconnect'], 1)
    reconnect_status = 1
    # 创建并启动重连线程
    reconnect_thread = threading.Thread(target=reconnect)
    reconnect_thread.daemon = True  # 设置为守护线程，主程序退出时自动结束
    reconnect_thread.start()
    logger.info("自动断连初始化")
    try:
        # 在主线程中运行系统托盘
        icon.run()
    except Exception as e:
        logger.error(e)
    finally:
        running = False
        reconnect_thread.join(timeout=1.0)  # 等待重连线程结束
        logger.info("自动断连已退出")